package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.douwong.student.R;
import com.douwong.student.adapter.PrepareLoadingAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.db.PrepareReaourceDBService;
import com.douwong.student.model.PrepareResource;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.JsonUtils;

import java.util.ArrayList;

/**e
 * 备课正在下载碎片
 * 
 * @author Administrator
 * 
 */
@SuppressLint("ValidFragment")
public class PrepareLoadingFragment extends Fragment {
	private View view;
	private ListView prepare_loading_listView;
	private PrepareLoadingAdapter adapter;
	private ArrayList<PrepareResource> list;
	private PrepareResource prepareResource;
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(CommonConfig.RESOURCE_UPDATE)) {
				for (int i = 0; i < list.size(); i++) {
					if (intent.getIntExtra("fileId", -1) == list.get(i).getId()) {
						try {
							View view = getViewByPosition(i,
									prepare_loading_listView);
							if (view != null) {
								long progress = intent.getLongExtra("pro", 0);
								ProgressBar load_pro = (ProgressBar) view
										.findViewById(R.id.load_pro);
								TextView pro_text = (TextView) view
										.findViewById(R.id.pro_text);
								String pro = FileUtils
										.formatFileSize(progress)
										+ "/"
										+ FileUtils.formatFileSize(list.get(i)
												.getFileSize());
								pro_text.setText(pro);
								load_pro.setProgress((int) (progress * 100 / list
										.get(i).getFileSize()));
								list.get(i).setCurrentPro(progress);

							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						break;
					}
				}
			} else if (action.equals(CommonConfig.GET_RESOURCE_LOAD)) {//开始下载
				//解析资源
				String resource = intent.getStringExtra("resource");
				prepareResource = JsonUtils.deserialize(resource,
						PrepareResource.class);
				
					prepareResource.setFilePath(FileUtils.RESOURCE_DIR
							+ prepareResource.getFileName());
					prepareResource.setLoading(true);
					PrepareReaourceDBService.getInstance(getActivity()).addLoading(
							prepareResource);
					list.add(prepareResource);
					adapter.notifyDataSetChanged();

					Intent loadAdd = new Intent();
					loadAdd.setAction(CommonConfig.RESOURCE_LOAD_ADD);
					getActivity().sendBroadcast(loadAdd);

					Intent loadIntent = new Intent();
					loadIntent.setAction(CommonConfig.BEGIN_LOAD_RESOURCE);
					loadIntent.putExtra("resource", resource);
					getActivity().sendBroadcast(loadIntent);
				
			} else if (action.equals(CommonConfig.RESOURCE_LOAD_COMPLETED)) {// 下载完成
				int fileId = intent.getIntExtra("fileId", -1);
				for (int i = 0; i < list.size(); i++) {
					if (fileId == list.get(i).getId()) {
						Intent changeIntent = new Intent();
						changeIntent
								.setAction(CommonConfig.CHANGE_RESOURCE_STATE);
						changeIntent.putExtra("loadState", "Loaded");
						changeIntent.putExtra("fileId", fileId);
						getActivity().sendBroadcast(changeIntent);
						//更新下载成功时间
						PrepareReaourceDBService.getInstance(getActivity()).upDateLoadTime(list.get(i));

						Intent completedIntent = new Intent();
						completedIntent
								.setAction(CommonConfig.RESOURCE_COMPLETED_ADD);
						completedIntent.putExtra("json",
								JsonUtils.serialize(list.get(i)));
						getActivity().sendBroadcast(intent);

						Intent reduceIntent = new Intent();
						reduceIntent
								.setAction(CommonConfig.RESOURCE_LOAD_REDUCE);
						getActivity().sendBroadcast(reduceIntent);
						list.remove(i);
						adapter.notifyDataSetChanged();
						break;
					}
				}
			}
		}

	};
	IntentFilter filter = new IntentFilter() {
		{
			addAction(CommonConfig.RESOURCE_UPDATE);
			addAction(CommonConfig.GET_RESOURCE_LOAD);
			addAction(CommonConfig.RESOURCE_LOAD_COMPLETED);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		getActivity().registerReceiver(receiver, filter);
		view = inflater.inflate(R.layout.prepare_loading_layout, null);		
		prepare_loading_listView = (ListView) view
				.findViewById(R.id.prepare_loading_listview);
		prepare_loading_listView.setOverScrollMode(View.OVER_SCROLL_NEVER);
		list = new ArrayList<PrepareResource>();
		list.clear();
		
		if(BaseApplication.sUserBean!=null){
			list.addAll(PrepareReaourceDBService.getInstance(getActivity())
				.queryLoading());
		}else{
//			Toast.makeText(getActivity(), R.string.login_please, Toast.LENGTH_LONG).show();
			return view;
		}
		
		
		if (list.size() > 0) {
			Intent intent = new Intent();
			intent.setAction(CommonConfig.RESOURCE_LOAD_COUNT);
			intent.putExtra("loadCount", list.size());
			getActivity().sendBroadcast(intent);
		}
		adapter = new PrepareLoadingAdapter(getActivity(), list,
				new PrepareLoadingOnClick());
		prepare_loading_listView.setAdapter(adapter);
		return view;
	}

	@SuppressLint("NewApi")
	public class PrepareLoadingOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			int position = (Integer) v.getTag();
			switch (v.getId()) {
			// 下载暂停停止
			case R.id.isupload_text:
				View loadView = getViewByPosition(position,
						prepare_loading_listView);
				TextView isupload_text = null;
				if (loadView != null) {
					isupload_text = (TextView) loadView
							.findViewById(R.id.isupload_text);
				}
				Intent intent = new Intent();
				if (!list.get(position).isPause()) {
					isupload_text.setBackground(getResources().getDrawable(
							R.mipmap.class_isupload));
					intent.setAction(CommonConfig.STOP_LOAD_RESOURCE);
					intent.putExtra("fileId", list.get(position).getId());
					getActivity().sendBroadcast(intent);
					list.get(position).setPause(true);
					list.get(position).setLoaded(false);
					list.get(position).setLoading(true);
					PrepareReaourceDBService.getInstance(getActivity())
							.upDateLoading(list.get(position));
				} else {
					isupload_text.setBackground(getResources().getDrawable(
							R.mipmap.class_load_paus));
					intent.setAction(CommonConfig.CONTINUE_LOAD_RESOURCE);
					intent.putExtra("resource", JsonUtils.serialize(list.get(position)));
					list.get(position).setPause(false);
					list.get(position).setLoaded(false);
					list.get(position).setLoading(true);
					getActivity().sendBroadcast(intent);
					PrepareReaourceDBService.getInstance(getActivity())
							.upDateLoading(list.get(position));
				}
				break;
			// 删除正在下载的任务
			case R.id.upload_delete_text:
				Intent changeIntent = new Intent();
				changeIntent.setAction(CommonConfig.CHANGE_RESOURCE_STATE);
				changeIntent.putExtra("loadState", "Delete");
				changeIntent.putExtra("fileId", list.get(position).getId());
				list.get(position).setLoading(false);
				list.get(position).setPause(false);
				list.get(position).setLoaded(false);
				PrepareReaourceDBService.getInstance(getActivity()).upDate(
						list.get(position));
				PrepareReaourceDBService.getInstance(getActivity()).deleteLoading(list.get(position).getId());
				getActivity().sendBroadcast(changeIntent);

				Intent reduceIntent = new Intent();
				reduceIntent.setAction(CommonConfig.RESOURCE_LOAD_REDUCE);
				getActivity().sendBroadcast(reduceIntent);

				Intent closeIntent = new Intent();
				closeIntent.setAction(CommonConfig.CLOSE_RESOURCE_LOAD);
				closeIntent.putExtra("fileId", list.get(position).getId());
				getActivity().sendBroadcast(closeIntent);

				FileUtils.deleteFile(list.get(position).getFilePath());// 删除本地为未下载完的文件
				list.remove(position);
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}

		}

	}

	public View getViewByPosition(int pos, ListView listView) {
		final int firstListItemPosition = listView.getFirstVisiblePosition();
		final int lastListItemPosition = firstListItemPosition
				+ listView.getChildCount() - 1;

		if (pos < firstListItemPosition || pos > lastListItemPosition) {
			return listView.getAdapter().getView(pos, null, listView);
		} else {
			final int childIndex = pos - firstListItemPosition;
			// Log.e("firstListItemPosition", firstListItemPosition + "");
			// Log.e("lastListItemPosition", lastListItemPosition + "");
			// Log.e("childIndex", childIndex + "");
			return listView.getChildAt(childIndex);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
	}
}
